package com.ruoyi.project.third;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.outboundbot.model.v20191226.AssignJobsRequest;
import com.aliyuncs.outboundbot.model.v20191226.AssignJobsResponse;
import com.aliyuncs.outboundbot.model.v20191226.CreateJobGroupRequest;
import com.aliyuncs.outboundbot.model.v20191226.CreateJobGroupResponse;
import com.aliyuncs.profile.DefaultProfile;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * 外呼 可使用AssignJobs循环多次向同一任务组下发任务，每次下发任务数建议25个job.
 */
@Component
@Slf4j
public class ALiYunCustomerUtil {

    /**
     * 执行外呼
     *
     * @return
     */
    public JSONObject execute (String accessKeyId, String accessSecret, String InstanceId, List <String> list,
            String scriptId, String jobGroupId) {
        JSONObject js = new JSONObject();
        DefaultProfile profile = DefaultProfile.getProfile("cn-shanghai", accessKeyId, accessSecret);
        IAcsClient client = new DefaultAcsClient(profile);
        AssignJobsRequest request = new AssignJobsRequest();
        request.setInstanceId(InstanceId);
        request.setJobGroupId(jobGroupId);
        request.setJobsJsons(list);
        try {
            AssignJobsResponse response = client.getAcsResponse(request);
            log.info("ALiYunCustomerUtil-》ClientException返回数据：{}", JSON.toJSONString(response));
            System.out.println(JSON.toJSONString(response));
            js.put("ErrCode", 0);
            js.put("ErrMsg", "成功");
            js.put("RequestId", "");
        } catch (ServerException e) {
            log.error("ALiYunCustomerUtil-》ClientException异常：{}", e);
            js.put("ErrCode", -100);
            js.put("ErrMsg", "异常");
            js.put("RequestId", "");
        } catch (ClientException e) {
            log.error("ALiYunCustomerUtil-》ClientException异常：{}", e);
            js.put("ErrCode", e.getErrCode());
            js.put("ErrMsg", e.getErrMsg());
            js.put("RequestId", e.getRequestId());
        }
        return js;
    }

    /**
     * JobsJson.N是个List，每个JobJson对应一个联系人(contact)。
     *
     * @return
     */
    public List <String> createJobsJson (List <Map <String, String>> userList) {
        if (ObjectUtils.isEmpty(userList)) {
            throw new RuntimeException("组装外呼参数失败,请联系运营人员");
        }
        List <String> jobs = new ArrayList <>();
        for (Map <String, String> map : userList) {
            JSONObject contact = new JSONObject();
            contact.put("phoneNumber", map.get("phoneNumber"));
            contact.put("honorific", map.get("honorific"));
            contact.put("name", map.get("name"));
            contact.put("referenceId", map.get("referenceId"));
            List <JSONObject> extras = new ArrayList <>();
            extras.add(new JSONObject().fluentPut("key", "自定义参数1").fluentPut("value", "1"));
            extras.add(new JSONObject().fluentPut("key", "自定义参数2").fluentPut("value", "2"));
            JSONObject job = new JSONObject();
            job.put("contacts", Collections.singletonList(contact));
            job.put("extras", extras);
            jobs.add(JSON.toJSONString(job));
        }
        return jobs;
    }


    public CreateJobGroupResponse createJobGroup (String accessKeyId, String accessSecret, String InstanceId,
            String scriptId) {
        // 强烈建议不要把AccessKey ID和AccessKey Secret保存到工程代码里，否则可能导致AccessKey泄露，威胁您账号下所有资源的安全。
        // 本示例以将AccessKey ID和 AccessKey Secret保存在环境变量为例说明。运行本示例代码前，请先配置环境变量。
        DefaultProfile profile = DefaultProfile.getProfile("cn-shanghai", accessKeyId, accessSecret);
        IAcsClient client = new DefaultAcsClient(profile);
        CreateJobGroupRequest request = new CreateJobGroupRequest();
        request.setJobGroupName(DateUtil.format(new Date(), "yyyyMMddHHmmss") + "零零工外呼作业组—" + InstanceId);
        request.setInstanceId(InstanceId);
        request.setScriptId(scriptId);
        request.setStrategyJson(JSON.toJSONString(createStrategy()));
        try {
            CreateJobGroupResponse response = client.getAcsResponse(request);
            log.info("createJobGroup:{}", JSON.toJSONString(response));
            return response;
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            log.info("ErrCode:{}", e.getErrCode());
            log.info("ErrMsg:{}", e.getErrMsg());
            log.info("RequestId:{}", e.getRequestId());
        }
        return null;
    }

    /**
     * AssignJobs接口也可以传入Strategy参数
     * Strategy优先级为AssignJobs > CreateJobGroup
     *
     * @return
     */
    private static JSONObject createStrategy () {
        JSONObject strategy = new JSONObject();
        strategy.put("maxAttemptsPerDay", 3); //号码每天最大呼叫次数
        strategy.put("minAttemptInterval", 10); //未接通情况下的重试时间间隔，单位为分钟
        strategy.put("name", UUID.randomUUID().toString()); //策略名称
        strategy.put("startTime", System.currentTimeMillis()); //开始时间戳
        strategy.put("endTime", System.currentTimeMillis() + 60 * 60 * 1000L); //结束时间戳
        List <JSONObject> workingTimes = new ArrayList <>(); // 可呼出的时间窗口，24小时制
        JSONObject workingTime0 = new JSONObject();
        workingTime0.put("beginTime", "09:00:00");
        workingTime0.put("endTime", "12:00:00");
        JSONObject workingTime1 = new JSONObject();
        workingTime1.put("beginTime", "14:00:00");
        workingTime1.put("endTime", "16:00:00");
        workingTimes.add(workingTime0);
        workingTimes.add(workingTime1);
        strategy.put("workingTime", workingTimes);
        return strategy;
    }


}
